package com.example.blog.modules.user.controller;

import com.example.blog.common.api.ApiResponse;
import com.example.blog.common.security.JwtTokenProvider;
import com.example.blog.modules.user.dto.OAuth2UserInfo;
import com.example.blog.modules.user.dto.UserDTO;
import com.example.blog.modules.user.service.OAuth2UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "OAuth2认证接口", description = "OAuth2认证相关接口")
@RestController
@RequestMapping("/api/oauth2")
@RequiredArgsConstructor
public class OAuth2Controller {
    
    private final OAuth2UserService oAuth2UserService;
    private final JwtTokenProvider jwtTokenProvider;
    
    @Operation(summary = "OAuth2登录回调")
    @GetMapping("/callback")
    public ApiResponse<UserDTO> oauth2Callback(Authentication authentication) {
        if (authentication instanceof OAuth2AuthenticationToken) {
            OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
            String provider = oauthToken.getAuthorizedClientRegistrationId();
            
            OAuth2UserInfo userInfo = oAuth2UserService.getOAuth2UserInfo(
                    provider,
                    oauthToken.getPrincipal().getAttributes()
            );
            
            UserDTO user = oAuth2UserService.processOAuth2User(userInfo);
            String token = jwtTokenProvider.generateToken(authentication);
            
            user.setToken(token);
            return ApiResponse.success(user);
        }
        
        return ApiResponse.error("不支持的认证类型");
    }
} 